
class BlogController < ApplicationController
  
  before_filter :set_history, :only => [ :edit, :index, :new, :view ]
  before_filter :authorized, :except => [ :index, :view ]
  
  # Non-AJAX Stuff
  def edit
    @post = Post.find(params[:id])
    unless request.get?
      @post.attributes = params[:post]
      if params[:commit] == 'Save'
        if @post.save
          redirect_to :action => :view, :id => @post
        else
          flash[:edit_post_error] = @post.errors.full_messages.join "<br />"
        end
      else
        @preview = @post.format_text
      end
    end
  end
  
  def index
    @posts = Post.find(:all, :order => "created_on DESC", :limit => 5)
  end
  
  def new
    if request.get?
      @post = Post.new
    else
      @post = Post.new(params[:post])
      if params[:commit] == 'Save'
        if @post.save
          redirect_to :action => :index
        else
          flash[:new_post_error] = @post.errors.full_messages.join "<br />"
        end
      else
        @preview = @post.format_text
      end
    end
  end
  
  def view
    @post = Post.find(params[:id])
  end
  
  # Remote Functions
  def remote_edit_preview
    @post = Post.find(params[:id])
    @post.attributes = params[:post]
    @preview = @post.format_text
  end
  
  def remote_new_preview
    @post = Post.new(params[:post])
    @preview = @post.format_text
  end
  
  def remote_save_edit
    @post = Post.find(params[:id])
    @saved = @post.update_attributes(params[:post])
  end
  
  def remote_save_new
    @post = Post.new(params[:post])
    @saved = @post.save
  end
  
  def remote_show_edit
    @post = Post.find(params[:id])
  end
  
  def remote_show_new
  end
  
end
